package put.poznan.qmese.matlab.parser;

import put.poznan.qmese.matlab.model.Addition;
import put.poznan.qmese.matlab.model.Chunk;
import put.poznan.qmese.matlab.model.Matrix;
import put.poznan.qmese.matlab.model.Memory;
import put.poznan.qmese.matlab.model.Multiplication;
import put.poznan.qmese.matlab.model.Operation;
import put.poznan.qmese.matlab.model.Substract;

public class MatrixParser {

	public Chunk parse(String input) throws ParserException {

		String[] leftRightPart = null;
		String rightPart = null;

		if (input.contains("=")) {
			leftRightPart = input.split("=");
			rightPart = leftRightPart[1];
		}

		try {
			if (rightPart.contains("[")) {
				return parseMatrix(leftRightPart[0], rightPart);
			} else if (rightPart.contains("*")) {
				String[] afterSplit = input.split("*");
				Multiplication op = new Multiplication();
				return parseOperation(op, afterSplit);
			} else if (rightPart.contains("+")) {
				String[] afterSplit = input.split("*");
				Addition op = new Addition();
				return parseOperation(op, afterSplit);
			} else if (rightPart.contains("-")) {
				String[] afterSplit = input.split("*");
				Substract op = new Substract();
				return parseOperation(op, afterSplit);
			}
		} catch (NullPointerException e) {
			Matrix matrix = Memory.getMatrix(input.replace(";", ""));
			System.out.println(matrix.toString());
		}
		return null;

	}

	private Matrix parseMatrix(String leftPart, String input) {

		input = input.replace("[", "");
		input = input.replace("]", "");

		String[] rowSplit = input.split("\\|");
		String[] columns;
		Matrix matrix = new Matrix();
		matrix.setId(leftPart.replace(";", ""));
		matrix.initialize(rowSplit.length, rowSplit[0].split(",").length);
		rowSplit.toString();

		for (int i = 0; i < rowSplit.length; i++) {
			columns = rowSplit[i].split(",");
			for (int j = 0; j < columns.length; j++) {
				matrix.set(i, j, Double.valueOf(columns[j]));
			}
		}

		return matrix;
	}

	private Operation parseOperation(Operation op, String[] split) {
		op.setMatrixA(split[0]);
		op.setMatrixB(split[1]);
		return op;
	}
}
